package cc.ok200.api.controller;

import cc.ok200.api.common.ApiException;
import cc.ok200.api.common.ApiRequest;
import cc.ok200.api.common.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 示例REST控制器
 */
@RestController
@RequestMapping("/")
public class IndexController {

    @GetMapping("download/{pathname}")
    public ResponseEntity<Resource> download(@PathVariable String pathname, HttpServletResponse response) throws IOException {

        Path filePath = Paths.get("upload", pathname);
        File file = filePath.toFile();

        // 确定文件的MIME类型
        String contentType = Files.probeContentType(filePath);
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        
        // 创建文件资源
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        
        // 设置HTTP标头
        HttpHeaders headers = new HttpHeaders();

        headers.add(HttpHeaders.CONTENT_DISPOSITION, 
                    "attachment; filename*=UTF-8''" + URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.toString()));
        
        // 构建并返回响应
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType(contentType))
                .contentLength(file.length())
                .body(resource);
    }
} 